package com.example.yyg.springframework.beans.factory.support;

import com.example.yyg.springframework.beans.BeansException;
import com.example.yyg.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{


    private InstantiationStrategy instantiationStrategy = new CglibInstantiationStategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Object bean = null;
        try {
            if (args == null) {
                bean = instantiationStrategy.instantiate(beanDefinition, beanName, null, null);
            } else {
                Class beanClass = beanDefinition.getBeanClass();
                for (Constructor constructor:beanClass.getDeclaredConstructors()) {
                    if (constructor.getParameterCount() == args.length) {
                        bean = instantiationStrategy.instantiate(beanDefinition, beanName, constructor, args);
                        break;
                    }
                }
            }
            addSingleton(beanName, bean);
            return bean;
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
    }



}
